/**
* @program: src
*
* @description:
*
* @author: Mr.chen
*
* @create: 2020-11-20 16:26
**/
package group

import (
	"ydd-im/service/api/models"
	"ydd-im/service/api/services/wsservice/client"
	mydb "ydd-im/service/api/tools/mysql/conn"
	"ydd-im/service/api/tools/util"
	"ydd-im/util/response"
	"errors"
	"fmt"
	"strings"
	"time"
)

/**
 * 创建群
 * @access  public
 * @param   int     userid  用户自增id
 * @param   int     sid  群签名id
 * @param   string     groupkey  群id
 * @param   []string     members  用户，多个以逗号隔开
 * @param   string     Name  群名称
 * @param   string     appkey  appkey
 * @return  mix
 */
func AddGroupIsCluster(userid, sid int, groupkey, name string, members []string) (err error) {
	if util.IsCluster() { // 如果是集群的
		resp,err :=   client.AddGroupIsCluster(userid, sid , groupkey, name , members)
		if err !=nil {
			return err
		}
		if resp.Code == response.SuccessCode {
			return nil
		}else{
			return errors.New(resp.Msg)
		}

	}else{
		err := AddGroup(userid, sid , groupkey, name , members)
		return err
	}

}
/**
 * 加入群，将指定的用户加入群
 * @access  public
 * @param   int     userid  用户id
 * @param   int     sid  群所属签名
 * @param   string     groupkey  群自定义id
 * @param   []string     members  群成员
 * @return  mix
 */
func AddGroupContactIsCluster(userid, sid int,groupkey string, members []string) (err error) {
	if util.IsCluster() { // 如果是集群的
		resp,err :=   client.AddGroupContactIsCluster(userid, sid , groupkey,members)
		if err !=nil {
			return err
		}
		if resp.Code == response.SuccessCode {
			return nil
		}else{
			return errors.New(resp.Msg)
		}
	}else{
		err := AddGroupContactSingle(userid, sid , groupkey , members)
		return err
	}
}
/**
 * 加入群逻辑类
 * @access  public
 * @param   int     userid  用户id
 * @param   int     sid  群所属签名
 * @param   string     groupkey  群自定义id
 * @param   []string     members  群成员
 * @return  mix
 */
func AddGroupContactSingle(userid, sid int, groupkey string, members []string )   error {
	//校验是否为空
	if userid <= 0 || len(groupkey) == 0 || len(members) ==0 {
		return errors.New("参数不合法")
	}
	// 查询数据库是否已经存在当前群
	modelgroup := new(models.Group)
	// 查询数据库是否存在
	var where []string
	var on string
	if sid >= 0 {
		on = fmt.Sprintf(" a.ownerid = b.id and b.sid = %d ", sid)
	}
	if ok := util.FilteredSQLInject(groupkey); ok {
		return errors.New("参数不合法")
	}
	where = append(where, fmt.Sprintf(" a.groupkey = '%s' ",  groupkey))
	field := "a.id,a.name,a.groupkey"
	groupJoinUserInfo, err := modelgroup.GetGroupJoinUserInfo(where, field, "", on, false)
	if err != nil {
		return err
	}
	if groupJoinUserInfo.Id <= 0 {
		return errors.New("当前群不存在，请重试")
	}
	dbconn,err := mydb.DBConn("w")
	if err != nil {
		return  err
	}
	tx, err := dbconn.Beginx() // 开启事务
	if err != nil {
		tx.Rollback()
		return err
	}
	var groupContact []*models.GroupContact
	// 查询当前的用户
	modelUser := new(models.User)
	var userWhere []string
	if len(members) >= 0 {
		inStr := strings.Join(members, ",")
		userWhere = append(userWhere, fmt.Sprintf("userkey in (%s)", inStr))
	}
	userField := "id"
	userList, err := modelUser.GetUserList(userWhere, userField, 0, 0, "")
	if err != nil {
		tx.Rollback()
		return errors.New(err.Error())
	}
	if len(userList) == 0 {
		tx.Rollback()
		return errors.New("群成员不能为空")
	}
	userIdList,_ := modelUser.Get_arr_column(userList)
	// 过滤当前已经加入群的用户
	modelGroupContact := new(models.GroupContact)
	var groupContactwhere []string
	useridStr := strings.Join(userIdList,",")
	groupContactwhere = append(groupContactwhere, fmt.Sprintf("ownerid in (%s)", useridStr))
	groupContactwhere = append(groupContactwhere, fmt.Sprintf("dstid = %d", groupJoinUserInfo.Id))
	groupContactwhere = append(groupContactwhere, fmt.Sprintf("cate = %d", 0))
	groupContactList,err := GetAllGroupContactList(where,"id,ownerid")
	if  err != nil {
		tx.Rollback()
		return errors.New("获取群成员失败")
	}
	createTime := util.GetCurrentDateTime()
	_,_ContactListMapOwnerids := modelGroupContact.Get_arr_column(groupContactList)
	for k, _ := range userList {
		if _, ok := _ContactListMapOwnerids[fmt.Sprintf("%d",userList[k].Id)];!ok {
			gr := &models.GroupContact{
				Ownerid:    userList[k].Id,
				Dstid:      groupJoinUserInfo.Id,
				Cate:       0,
				Memo:       fmt.Sprintf("%d 添加的好友",userid),
				Createtime: createTime,
				Isowner:    0,
			}
			groupContact = append(groupContact, gr)
		}
	}
	if len(groupContact) == 0 {
		tx.Rollback()
		return errors.New("群成员数据不合法")
	}
	// 插入群联系人
	_, err = new(models.GroupContact).BatchInsertGroupContact(groupContact)
	if err != nil {
		tx.Rollback()
		return errors.New("加入群失败")
	}
	tx.Commit()
	return nil
}

// 根据userid，groupid获取群信息
func GetGroupUserInfo(userid, groupid int) (data bool, err error) {
	//校验是否为空
	if userid <= 0 || groupid <= 0 {
		return false, errors.New("userid,groupid不能为空")
	}
	// 查询数据库是否存在
	groupcontact := new(models.GroupContact)
	groupcontactInfo, err := groupcontact.GetGroupContactByCondition(userid, groupid)
	if err != nil {
		return false, errors.New(err.Error())
	}
	if groupcontactInfo.Id > 0 { // 存在
		return true, nil
	} else { // 当前群不存在
		return false, nil
	}
}

/**
 * 添加联系人
 * @access  public
 * @param   int     userid  用户id
 * @param   int     groupid  群id
 * @return  mix
 */
func AddGroupContact(userid, groupid int) (err error) {
	//校验是否为空
	if userid <= 0 || groupid <= 0 {
		return errors.New("userid,groupid不能为空")
	}
	// 查询数据库是否存在
	groupcontact := new(models.GroupContact)
	gc := &models.GroupContact{Ownerid: userid, Dstid: groupid, Cate: 0, Memo: "", Createtime: time.Now()}
	_, err = groupcontact.AddGroupContact(gc)
	if err != nil {
		return errors.New(err.Error())
	}
	return nil
}

// 获取群列表
func GetAllGroupList(sid int, userid int) (group []models.Group, err error) {
	//校验是否为空
	if sid < 0 || userid <= 0 {
		return group, errors.New("参数不合法")
	}
	// 查询数据库是否存在
	modelGroup := new(models.Group)
	group, err = modelGroup.GetAllGroupJoinGroupContactList(sid, userid)
	if err != nil {
		return group, err
	}
	return group, nil
}

/**
 * 获取用户所属群
 * @access  public
 * @param   int     sid  签名
 * @param   int     userid  用户id
 * @return  mix
 */
func GetAllJoinGroupList(sid int, userid int) (group []models.Group, err error) {
	//校验是否为空
	if sid < 0 || userid <= 0 {
		return group, errors.New("参数不合法")
	}
	// 查询数据库是否存在
	modelGroupContact := new(models.GroupContact)
	group, err = modelGroupContact.GetAllGroupContactJoinGroupList(sid, userid)
	if err != nil {
		return group, err
	}
	return group, nil
}

/**
 * 获取群用户
 * @access  public
 * @param   string     groupid  群id
 * @return  mix
 */
func GetAllGroupContactList(where []string, field string) (groupContact []models.GroupContact, err error) {
	//校验是否为空
	if len(field) == 0 {
		return groupContact, errors.New("参数不合法")
	}
	// 查询数据库是否存在
	modelGroupContact := new(models.GroupContact)
	groupContact, err = modelGroupContact.GetAllGroupContactList(where, field, 0, 0, "")
	if err != nil {
		return groupContact, err
	}
	return groupContact, nil
}

/**
 * 获取数组中的某一列
 * @param array arr 数组
 * @param string key_name  列名
 * @return array  返回那一列的数组
 */
func Get_arr_column(arr []models.GroupContact) []int {
	newArr := make([]int, 0)
	for k, _ := range arr {
		newArr = append(newArr, arr[k].Ownerid)
	}
	return newArr
}

/**
 * 添加群，将指定的用户加入群
 * @access  public
 * @param   int     userid  用户id
 * @param   int     groupid  群id
 * @return  mix
 */
func AddGroup(userid, sid int, groupkey, name string, members []string) (err error) {
	//校验是否为空
	if userid <= 0 || len(groupkey) == 0 || len(name) == 0 || len(members) ==0 {
		return errors.New("参数不合法")
	}
	// 查询数据库是否已经存在当前群
	modelgroup := new(models.Group)
	// 查询数据库是否存在
	var where []string
	var on string
	if sid >= 0 {
		on = fmt.Sprintf(" a.ownerid = b.id and b.sid = %d ", sid)
	}
	if ok := util.FilteredSQLInject(name); ok {
		return errors.New("参数不合法")
	}
	if len(groupkey) > 0 {
		if ok := util.FilteredSQLInject(groupkey); ok {
			return errors.New("参数不合法")
		}
		where = append(where, fmt.Sprintf(" a.name = '%s' or a.groupkey = '%s' ", name, groupkey))
	}else{
		where = append(where, fmt.Sprintf(" a.name = '%s' ", name))
	}
	field := "a.id,a.name,a.groupkey"
	groupJoinUserInfo, err := modelgroup.GetGroupJoinUserInfo(where, field, "", on, false)
	if err != nil {
		return err
	}
	if groupJoinUserInfo.Id > 0 {
		return errors.New("当前群名称已存在")
	}
	dbconn,err := mydb.DBConn("w")
	if err != nil {
		return  err
	}
	tx, err := dbconn.Beginx() // 开启事务
	if err != nil {
		return err
	}

	// 查询数据库是否存在
	createTime := util.GetCurrentDateTime()
	g := &models.Group{Name: name, Ownerid: userid, Cate: 0, Icon: "", Memo: name, Createtime: createTime,GroupKey:groupkey}
	restId, err := modelgroup.AddGroupTx(g,tx)
	if err != nil {
		tx.Rollback()
		return errors.New(err.Error())
	}
	var groupContact []*models.GroupContact
	restIdint := util.Int64Toint(restId)
	// 查询当前的用户
	modelUser := new(models.User)
	var userWhere []string
	if len(members) >= 0 {
		//inStr := strings.Join(members, ",")
		var instr string
		for i := 0; i < len(members); i++ {
			if i == 0 {
				instr +=fmt.Sprintf("'%s'",members[i])
			} else {
				instr +=fmt.Sprintf(",'%s'",members[i])
			}
		}
		userWhere = append(userWhere, fmt.Sprintf("userkey in (%s)", instr))
	}
	userField := "id"
	userList, err := modelUser.GetUserListIn(userWhere, userField, 0, 0, "")
	if err != nil {
		fmt.Println(err)
		err = tx.Rollback()
		fmt.Println("错误",err)
		return errors.New(err.Error())
	}
	if len(userList) == 0 {
		tx.Rollback()
		return errors.New("群成员不能为空")
	}
	for k, _ := range userList {
		var isowner int
		if userList[k].Id == userid {
			isowner = 1
		}
		gr := &models.GroupContact{
			Ownerid:    userList[k].Id,
			Dstid:      restIdint,
			Cate:       0,
			Memo:       "创建"+name+"群添加的好友",
			Createtime: createTime,
			Isowner:isowner,
		}
		groupContact = append(groupContact, gr)
	}
	// 插入群联系人
	_, err = new(models.GroupContact).BatchInsertGroupContactTx(groupContact,tx)
	if err != nil {
		tx.Rollback()
		return errors.New("创建群失败")
	}
	tx.Commit()
	return nil
}
